package org.mspring.mlog;

import org.apache.commons.lang3.StringUtils;
import org.mspring.nbee.web.WebUtils;
import org.mspring.nbee.web.exception.ErrorCodeException;
import org.mspring.nbee.web.exception.OperateException;
import org.mspring.nbee.web.view.json.JsonResult;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Gao Youbo
 * @since 2015-01-01 20:21
 */
public class ExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv = new ModelAndView();
        String xRequestedWith = request.getHeader("X-Requested-With");
        String xDataType = request.getHeader("json");
        if (StringUtils.equalsIgnoreCase(xRequestedWith, "XMLHttpRequest")) {
            final JsonResult result = new JsonResult();
            result.setSuccess(false);
            if (ex instanceof ErrorCodeException) {
                ErrorCodeException errorCodeException = (ErrorCodeException) ex;
                result.setCode(errorCodeException.getErrorCode());
                result.setMessage(errorCodeException.getMessage());
            } else {
                result.setMessage(ex.getMessage());
            }
            mv.setView(new View() {
                @Override
                public String getContentType() {
                    return "application/json";
                }

                @Override
                public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
                    FileCopyUtils.copy(WebUtils.toBrowserJson(result), response.getWriter());
                }
            });
        } else {
            if (ex instanceof OperateException) {
                mv.setViewName("/prompt");
                mv.getModel().put("ex", ex);
                mv.getModel().put("message", ex.getMessage());
            } else {
                String message = ex.getMessage();
                if (ex instanceof ErrorCodeException) {
                    ErrorCodeException errorCodeException = (ErrorCodeException) ex;
                    message = "错误码：" + errorCodeException.getErrorCode() + "<br/> 异常消息：" + ex.getMessage();
                } else {
                    message = ex.getMessage();
                }
                mv.setViewName("/exception");
                mv.getModel().put("ex", ex);
                mv.getModel().put("message", message);
            }
        }
        return mv;
    }
}
